package com.gzist.elderlyserviceplatform.interceptors;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * 路由拦截器
 */
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 放行的请求路径(swagger2版)
        List<String> patterns = new ArrayList<>();
        patterns.add("/swagger-resources/**");
        patterns.add("/webjars/**");
        patterns.add("/v2/**");
        patterns.add("/swagger-ui.html");
        patterns.add("/doc.html");
        patterns.add("/api/admin/user/login");
        patterns.add("/api/client/user/login");
        patterns.add("/api/common/**");
        patterns.add("/chat/**");
        patterns.add("/ws/chat/**");
        // Swagger3版
        patterns.add("/v3/api-docs/**");          // OpenAPI规范接口
        patterns.add("/swagger-ui/**");           // 新版UI路径（注意结尾斜杠）
        patterns.add("/swagger-ui");              // 无斜杠情况兼容

        // saToken拦截器
        registry.addInterceptor(new SaInterceptor(handler -> {
                    SaRouter.match("/**")
                            // 使用正确的路径排除规则
                            .notMatch(patterns.toArray(new String[0]))  // 排除Swagger接口路径
                            .check(r -> {
                                StpUtil.checkLogin();  // 检查用户登录状态
                            });
                })).addPathPatterns("/**");
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/");

        registry.addResourceHandler("/v3/api-docs/**")
                .addResourceLocations("classpath:/swagger/");

        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }


    /**
     * 注入jwt模式
     */
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }
}

